package dyyx;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

public class CacheTest {
	
	private static final String DATEFORMAT = "yyyy.MM.dd HH:mm:ss SSS";

	private static LoadingCache<Integer, String> cache = null;
	
	private static Random rand = new Random();
	
	public static void main(String[] args) throws Exception {	
		
	      cache = CacheBuilder.newBuilder()
	    		 
	    		// Without this will return zero for all statistics
	    		.recordStats()
                .maximumSize(7)
                // .refreshAfterWrite(3, TimeUnit.SECONDS)
                //软引用
                // .softValues() 
                .expireAfterWrite(3, TimeUnit.SECONDS)
                // .expireAfterAccess(duration, unit)
                .build(new CacheLoader<Integer, String>() {
                    @Override
                    public String load(Integer key) throws Exception {
                    	if(key>=3){
                    		// com.google.common.cache.CacheLoader$InvalidCacheLoadException: CacheLoader returned null for key 3
                    		//return null;
                    		return "NULL";
                    	}                   	
                	    SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
                	    
                	    
                	    if(rand.nextInt(3)<=0){
                	    	throw new Exception("load error,key="+key);
                	    }
                	           	    
                        return key+"_"+sdf.format(new Date());
                    }
                });
		
	    for(int i=0;i<5;i++){
	    	run(5);
	    	System.out.println(cache.size()+","+cache.stats());
			Thread.sleep(1000);
	    }
	    
	    cache.invalidateAll();
	    run(10);
	    
    	System.out.println(cache.size()+","+cache.stats());

	    
	}
	
	private static void run(int num)throws Exception{
		for(int i=0;i<num;i++){
			try{
			    System.out.println(i+"###"+cache.get(i));
			}catch(Throwable e){
				System.out.println("load error,key="+i+","+e);
			}
		}
	}
}
